<?php


namespace app\service\utils;


use app\common\exception\ApiException;

class QqMapService
{
    protected $key;

    public function __construct()
    {
        $this->key = config('map.tencent_key');
    }

    /**
     * 根据地址获取经纬度
     * @param $address
     * @return array
     * @throws \Exception
     */
    public function getCoordinate($address)
    {
        $url = "https://apis.map.qq.com/ws/geocoder/v1/?address=$address&output=JSON&key=" . $this->key;

        $result = curl_get($url);
        if(!$result){
            throw new ApiException('请填写详细地址');
        }
        $arr = json_decode($result, true);
        if ($arr['status'] !== 0) {
            throw new \Exception($arr['message']);
        }
        $lng = $arr['result']['location']['lng'];
        $lat = $arr['result']['location']['lat'];
        $cityCode = $arr['result']['ad_info']['adcode'];
        return ['lng' => $lng, 'lat' => $lat, 'city_code' => $cityCode];
    }

    /**
     * 获取经纬度信息
     * @param $lng
     * @param $lat
     * @return mixed
     * @throws \Exception
     */
    public function getAddressInfo($lng, $lat)
    {
        $location = $lat . ',' . $lng;
        $url = "https://apis.map.qq.com/ws/geocoder/v1/?location={$location}&output=JSON&key=" . $this->key;
        $result = curl_get($url);
        $arr = json_decode($result, true);
        if ($arr['status'] !== 0) {
            throw new \Exception($arr['message']);
        }
        $res = $arr['result'];
        return $res;
    }
}